package com.jianyitech.asr.controller;


import com.jianyitech.asr.exception.BizException;
import com.jianyitech.asr.utils.AuthConstant;
import com.jianyitech.asr.utils.DateUtil;
import com.jianyitech.asr.utils.Md5Util;
import com.jianyitech.asr.utils.StringUtil;
import com.jianyitech.asr.vo.TenantVo;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 基础控制器
 */
public class BaseController {
    private static final String UNKNOWN_KEY = "unknown";
    public HttpServletRequest getCurrentRequest(){
        return ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
    }

    public String getIpAddr() {
        String ip = null;
        int index = 0;
        try {
            HttpServletRequest request = getCurrentRequest();
            ip = request.getHeader("x-forwarded-for");
            // Proxy-Client-IP 这个一般是经过apache http服务器的请求才会有，用apache http做代理时一般会加上Proxy-Client-IP请求头，而WL-Proxy-Client-IP是他的weblogic插件加上的头。
            if (ip == null || ip.length() == 0 || UNKNOWN_KEY.equalsIgnoreCase(ip)) {
                ip = request.getHeader("Proxy-Client-IP");
            }
            if (ip == null || ip.length() == 0 || UNKNOWN_KEY.equalsIgnoreCase(ip)) {
                ip = request.getHeader("WL-Proxy-Client-IP");
            }
            if (ip == null || ip.length() == 0 || UNKNOWN_KEY.equalsIgnoreCase(ip)) {
                ip = request.getRemoteAddr();
            }
            if (StringUtil.isEmpty(ip)) {
                return "";
            }
            index = ip.indexOf(',');

            if (index != -1) {
                return ip.substring(0, index);
            } else {
                return ip;
            }
        } catch (Exception e) {
            return "";
        }
    }

    //校验
    public void check(TenantVo vo) {
        long ts = DateUtil.getTimestamp();
        long diff = Math.abs(ts - vo.getTs());
        //首先判断appId是否匹配
        if (diff > 180) {
            throw new BizException("间隔时间大于180秒，检验失败");
        } else {
            //生成MD5加密串与sign对比
            String str = Md5Util.encode(vo.getAppId() + AuthConstant.Check.APP_SECRET + vo.getTs()).toLowerCase();
            if (!str.equals(vo.getSign())) {
                throw new BizException("sign值不匹配，检验失败");
            }
        }
    }
}